<template>
  <img class="yowin-img" :src="localSrc" />
</template>
<script>
import { reactive, toRefs, watch } from "vue";
import defaultAvatar from "../../assets/images/default_avator.png";
export default {
  props: {
    src: {},
    defaultImg: {
      default: defaultAvatar,
    },
  },
  setup(props) {
    const state = reactive({
      localSrc: props.defaultImg,
      lastestSrc: "",
    });
    const onerror = (e) => {
      console.log("img-error", e);
      let strUrl = `${e.path[0].src}`;
      // const src = Filefilter(strUrl);
      // if (src === state.lastestSrc) {
      if (strUrl.startsWith("data:image/png;base64,")) {
        console.log("error-success");
        state.localSrc = props.defaultImg;
      } else {
        if (strUrl === state.lastestSrc) {
          console.log("error-success");
          state.localSrc = props.defaultImg;
        }
      }
    };
    const onload = (e) => {
      console.log("img-load 执行", e.path[0].src, state.lastestSrc);
      let strUrl = `${e.path[0].src}`;
      console.log("类型为", typeof strUrl, strUrl);

      /*   if (strUrl.startWith("file://")) {
        strUrl = strUrl.replace("file://", "");
      } */

      // const src = Filefilter(strUrl);
      // if (strUrl.indexOf("data:image/png;base64,") > 0) {
      if (strUrl.startsWith("data:image/png;base64,")) {
        console.log("是base64");
        console.log("load-success");
        state.localSrc = state.lastestSrc;
      } else {
        console.log("不是base64");
        if (strUrl === state.lastestSrc) {
          console.log("load-success");
          state.localSrc = state.lastestSrc;
        }
      }
    };
    const Filefilter = (url) => {
      const reg = "file://";
      // if (url.indexOf(reg) === -1) {
      console.log("字符串", url);
      let strUrl = `${url}`;
      if (!strUrl.startWith(reg)) {
        return url;
      }
      return strUrl.replace(reg, "");
    };
    watch(
      () => props.src,
      (newVal, oldVal) => {
        // console.log('newVal:',newVal,'oldVal:',oldVal);
        if (!newVal) {
          return;
        }
        state.lastestSrc = newVal;
        // state.localSrc = newVal
        const imgEl = document.createElement("img");
        imgEl.onload = onload;
        imgEl.onerror = onerror;
        imgEl.src = newVal;
      },
      { immediate: true }
    );
    return {
      ...toRefs(state),
      onerror,
      onload,
    };
  },
};
</script>
<style lang="less" scoped>
.yowin-img {
  height: 100%;
  width: 100%;
  display: block;
  border-radius: inherit;
}
</style>